﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using MySql.Data.MySqlClient;
using YmtAuth.Domain;
using YmtAuth.Domain.Repository;
using YmtSystem.CrossCutting;
using YmtAuth.Dto;

namespace YmtAuth.Repository.MySQL
{
    public class SellerOnlineStatusRepository : MySQLRepository<SellerOnlineStatusOp>, ISellerOnlineStatusRepository
    {
        public SellerOnlineStatusRepository()
            : base(ConfigurationManager.AppSettings["SellerOnlineStatus_MySQLConnString"], "SellerOnlineStatus")
        {
            
        }

        public int SaveSellerAppOnlineStatus(SellerOnlineStatusOp sellerOnlineStatus)
        {
            var querySQL = "select UserId from SellerOnlineStatus where UserId=@UserId AND OpType=@OpType limit 1";
            var queryPar = this.Parameters
                               .AddInt("@UserId", sellerOnlineStatus.UserId)
                               .AddString("@OpType", sellerOnlineStatus.OpType).Build();

            using (var conn = new MySqlConnection(this.connString))
            {
                var sellerStatus = conn.Query<SellerOnlineStatusOp>(querySQL, queryPar, commandType: CommandType.Text).FirstOrDefault();
                if (sellerStatus == null)
                {
                    try
                    {
                        return Convert.ToInt32(Insert(sellerOnlineStatus, false));
                    }
                    catch (MySqlException ex)
                    {
                        if (ex.Number == 1062)
                            return 1062;
                        throw;
                    }
                }
                else
                {
                    var upSQL = "update SellerOnlineStatus set `LastUpdateTime`=sysdate(),`Op`=@Op,`OpTime`=@OpTime where `UserId`=@UserId AND `OpType`=@OpType";
                    var upPar = this.Parameters
                                    .AddInt("@UserId", sellerStatus.UserId)
                                    .AddString("@Op", sellerOnlineStatus.Op)
                                    .AddDateTime("@OpTime", sellerOnlineStatus.OpTime)
                                    .Add("@OpType", sellerOnlineStatus.OpType).Build();
                    return conn.Execute(upSQL, upPar, commandType: CommandType.Text);
                }
            }
        }
    }
}
